<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind" label-width="120px">
      <uni-forms-item name="parent_id" label="上级" v-if="formData.parent_id">
    		<uni-data-select
    			 collection="mydb-department"
    			 field="_id as value, name as text"
    			 v-model="formData.parent_id"
           :disabled="true"
    		 />
    </uni-forms-item>
      <uni-forms-item name="name" label="人员名称" required>
        <uni-easyinput v-model="formData.name"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="description" label="手机号码">
        <uni-easyinput v-model="formData.description"></uni-easyinput>
      </uni-forms-item>
	  <uni-forms-item name="num" label="人员编号">
	    <uni-easyinput v-model="formData.num"></uni-easyinput>
	  </uni-forms-item>
      <uni-forms-item name="owner" label="部门负责人">
        <uni-data-select collection="uni-id-users" field="_id as value, nickname as text" v-model="formData.owner"
          :multiple="true" />
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
import { validator } from '../../js_sdk/validator/mydb-department.js';

const db = uniCloud.database();
const dbCmd = db.command;
const dbCollectionName = 'mydb-department';

function getValidator(fields) {
  let result = {}
  for (let key in validator) {
    if (fields.includes(key)) {
      result[key] = validator[key]
    }
  }
  return result
}



export default {
  data() {
    let formData = {
      "name": "",
      "type": "employee",
      "parent_id": "",
      "owner": [],
      "members": [],
      "description": "",
	  "num":""
    }
    return {
      formData,
      rules: {
        ...getValidator(Object.keys(formData))
      }
    }
  },
  onReady() {
    this.$refs.form.setRules(this.rules)
  },
  onLoad(e) {
    if (e.parent_id) {
      this.formData.parent_id = e.parent_id
    }
	if (e.id) {
	  const id = e.id
	  this.formDataId = id
	  this.getDetail(id)
	}
  },
  methods: {
    /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
            
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      },
    /**
     * 验证表单并提交
     */
    submit() {
      uni.showLoading({
        mask: true
      })
      this.$refs.form.validate().then((res) => {
        return this.submitForm(res)
      }).catch(() => {
      }).finally(() => {
        uni.hideLoading()
      })
    },

    /**
     * 提交表单
     */
    submitForm(value) {
		value.type='employee'
      return this.formData._id ? db.collection(dbCollectionName).add(value).then((res) => {
        uni.showToast({
          title: '新增成功'
        })
        this.getOpenerEventChannel().emit('refreshData')
        setTimeout(() => uni.navigateBack(), 500)
      }).catch((err) => {
        uni.showModal({
          content: err.message || '请求服务失败',
          showCancel: false
        })
      }) : db.collection(dbCollectionName).add(value).then((res) => {
        uni.showToast({
          title: '新增成功'
        })
        this.getOpenerEventChannel().emit('refreshData')
        setTimeout(() => uni.navigateBack(), 500)
      }).catch((err) => {
        uni.showModal({
          content: err.message || '请求服务失败',
          showCancel: false
        })
      })
    }
  }
}
</script>
